package com.bnz.listener;

import com.bnz.pojo.Product;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebListener
public class MyServletContextListener implements ServletContextListener, ServletContextAttributeListener {

	//1. application组件创建和销毁的监听
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		//1.1 定义一组商品
		Product p1 = new Product("1001","海尔洗衣机",1200,100);
		Product p2 = new Product("1002","联想电脑",5000,200);
		Product p3 = new Product("1003","华为手机",3500,300);
		Product p4 = new Product("1004","TCL电视",1900,300);
		Product p5 = new Product("1005","洽洽瓜子",6,400);
		Product p6 = new Product("1006","海飞丝洗发水",30,200);
		Product p7 = new Product("1007","双飞燕鼠标",20,500);
		Product p8 = new Product("1008","OPPO手机",2300,400);
		Product p9 = new Product("1009","康师傅方便面",5,500);
		Product p10 = new Product("1010","格力空调",2200,100);
		//1.2 放到一个Map中
		Map<String,Product> productMap = new HashMap<>();
		productMap.put(p1.getPid(),p1);
		productMap.put(p2.getPid(),p2);
		productMap.put(p3.getPid(),p3);
		productMap.put(p4.getPid(),p4);
		productMap.put(p5.getPid(),p5);
		productMap.put(p6.getPid(),p6);
		productMap.put(p7.getPid(),p7);
		productMap.put(p8.getPid(),p8);
		productMap.put(p9.getPid(),p9);
		productMap.put(p10.getPid(),p10);
		//1.3 将集合放到上下文路径中
		sce.getServletContext().setAttribute("products",productMap);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("application被销毁。。。");
	}
	//2. application组件属性值改变的监听
	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {
		System.out.println("application属性值添加。。。");
	}

	@Override
	public void attributeRemoved(ServletContextAttributeEvent event) {
		System.out.println("application属性值移除。。。");
	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent event) {

	}

}
